// 菜单栏权限
const { MongoClient, ServerApiVersion } = require('mongodb')
let dayjs = require('dayjs')
const { generateToken } = require('../utils/getToken')
const { dataToWrite } = require('../utils/getLogs')
const { generateRandomSerialNumber } = require('../utils/getSerialNumber')
const { query } = require('express')
const { removeEmptyData } = require('../utils/getRemoveEmptyData')

// 数据库地址
const uri = 'mongodb://localhost:27017/libraryDB'

// 连接数据库
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
})

const filesQuery = async (data) => {
  try {
    await client.connect()
    // 获取数据库对象
    const db = client.db('libraryDB')
    // 获取文件表
    const filesDb = db.collection('files')
    // 构造查询条件
    const condition = []
    Object.keys(query).forEach((key) => {
      // 如果值不为空，则构造模糊查询条件
      if (data[key]) {
        const regex = new RegExp(data[key])
      }
    })
    console.log(removeEmptyData(data), 333)
    const res = await filesDb.find(removeEmptyData(data)).limit(10)
    const list = []
    await res.forEach((element) => {
      list.push(element)
    })
    if (res) {
      return {
        msg: '查询文件表成功',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        msgCode: 10000,
        data: {
          total: list.length,
          list,
          success: true,
        },
      }
    }
  } catch (error) {
    console.log(error)
    dataToWrite(generateRandomSerialNumber(data))
    return {
      msg: '服务器异常',
      success: false,
      error,
    }
  }
}
module.exports = { filesQuery }
